﻿using Newtonsoft.Json;
using PanhuaWin.WMS2NC888;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PanhuaWin.工厂.仓库.下线
{
    public partial class Form补推 : Form
    {
        public Form补推()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            sendToNC产成品(textBox1.Text);
        }

        public void sendToNC产成品(string VolumeCodeNew)
        {

                string sqlbody = @"SELECT [guid], [Bguid], [DocCode], [RowNumber], [WorkShopCode], [WarehouseCode], [StorageLocation], [T_CONTRACT_CODE],
                                [T_ORDER], [T_GOOD_UNIT], [T_GOOD_NUM], [T_GOOD_PRICE], [T_GOOD_MONEY], [VolumeCode], [VolumeCodeNew], [InventoryCode], 
                                [Size], [Thick], [Width], [Material], [Address], [Weight], [CID], [Virtual], [FaceStatus], [FaceDone], [NetWeight],
                                [Remark], [ProductDate],Grade,Meter,ZinCeng,PingMing,PackageType,Customer
                                FROM      Bus_StockInVolume 
                                where 1=1 and VolumeCodeNew='" + VolumeCodeNew + "' order by RowNumber  ";

                DataTable dtBody = pub.GetDataTable(pub.ConnectionString, sqlbody);
                if (dtBody != null && dtBody.Rows.Count > 0)
                {
                    NCModel.FinishedProductsInBillModel setInboundModel = new NCModel.FinishedProductsInBillModel();
                    //setInboundModel.corpName = "";
                    setInboundModel.region = "华中";
                    setInboundModel.ceateDate = "2022-10-13";
                    //查询公司名称 公司编号
                    string sqlworkshop = @"SELECT  [WorkShopName]  FROM [Dic_WorkShop] where WorkShopCode = '3001'";
                    DataTable dtWorkShop = pub.GetDataTable(pub.ConnectionString, sqlworkshop);
                    if (dtWorkShop != null && dtWorkShop.Rows.Count > 0)
                    {
                        setInboundModel.corpName = dtWorkShop.Rows[0]["WorkShopName"].ToString();
                    }
                    else
                    {
                        MessageBox.Show("未能根据当前入库单公司编号查到对应的公司名称");
                        return;
                    }
                    // setInboundModel.cWarehouseName = dtBody.Rows[0]["WarehouseCode"].ToString();
                    setInboundModel.cWarehouseName = "涪镀锌一线成品库";
                    setInboundModel.cWhsmanagerCode = "";
                    setInboundModel.deptName = "";
                    setInboundModel.cbizCode = "";
                    setInboundModel.remarks = "";

                    List<NCModel.Item> itemList = new List<NCModel.Item>();
                    for (int i = 0; i < dtBody.Rows.Count; i++)
                    {
                    NCModel.Item item = new NCModel.Item();
                    //明细ID
                    item.rowNo = dtBody.Rows[0]["Bguid"].ToString();
                    //存货编码
                    item.cinvbascode = dtBody.Rows[0]["InventoryCode"].ToString();
                    //批次号
                    item.vbatchcode = dtBody.Rows[0]["VolumeCodeNew"].ToString(); ;
                    //入库数量
                    //decimal.TryParse(dtBody.Rows[0]["Weight"].ToString(), out decimal a);
                    //decimal 重量 = Math.Round(a, 4);
                    item.ninnum = dtBody.Rows[0]["Weight"].ToString();
                    //入库日期
                    item.dbilldate = DateTime.Parse(dtBody.Rows[0]["ProductDate"].ToString()).ToString("yyyy-MM-dd");

                    //颜色 只有彩涂卷才有颜色
                    if (dtBody.Rows[0]["PingMing"] != null && !string.IsNullOrEmpty(dtBody.Rows[0]["PingMing"].ToString()))
                    {
                        if (dtBody.Rows[0]["PingMing"].ToString().Contains("彩涂"))
                        {
                            item.vfree1 = dtBody.Rows[0]["Color"].ToString();
                        }
                        else
                        {
                            item.vfree1 = "";
                        }
                    }

                    //长度
                    item.vfree2 = dtBody.Rows[0]["Meter"].ToString();
                    //产地
                    if (string.IsNullOrEmpty(dtBody.Rows[0]["Address"]?.ToString()))
                    {
                        item.vfree3 = "万达";
                    }
                    else
                    {
                        item.vfree3 = dtBody.Rows[0]["Address"].ToString();
                    }


    

                    //表面状态  
                    item.vfree4 = "常规";
                    //表面厚度（锌层
                    item.vfree5 = "普通";
                    //等级 
                    item.vuserdef8 = dtBody.Rows[0]["Grade"].ToString();
                    //包装
                    item.vuserdef10 = dtBody.Rows[0]["PackageType"].ToString();
                    //客户
                    item.pk_defdoc13 = dtBody.Rows[0]["Customer"].ToString();

                    item.nprice = "";
                    item.nmny = "";
                    item.pk_defdoc11 = "";
                    item.pk_defdoc12 = "";
                    item.vnotebody = "";
                    item.vuserdef9 = "";
                    DateTime.TryParse(dtBody.Rows[0]["ProductDate"].ToString(), out DateTime date);
                    item.scrq = date.ToString("yyyy-MM-dd");
                    itemList.Add(item);
                }


                    setInboundModel.items = itemList;

                    string jsonStr = JsonConvert.SerializeObject(setInboundModel);

                    //XmlDocument xml  = (XmlDocument)JsonConvert.DeserializeXmlNode(jsonStr,"root");
                    ExternalSystemToNcItfPortTypeClient client = new ExternalSystemToNcItfPortTypeClient();
                    string responseStr = client.finishedProductsInBill(jsonStr);
                    NCModel.NCResponseModel nCResponse = JsonConvert.DeserializeObject<NCModel.NCResponseModel>(responseStr);
                    //调用成功，改写NC状态
                    if (nCResponse.state == 0)
                    {
                        //string sqlUpdate = @"update Bus_StockInV set SendToNCReturnValue = '" + nCResponse.result + "',IsSendToNC = 'Y' ,SendToNCDate = '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' where docCode = '" + docCode + "'";
                        //int r = pub.ExecuteSql(pub.ConnectionString, sqlUpdate, "原料卷入库发送到NC");
                        //if (r < 1)
                        //{
                        //    MessageBox.Show("更新是否成功发送到NC失败");
                        //}
                    }
                    MessageBox.Show("抛送NC结果：" + nCResponse.msg);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            sendToNC产成品2(maskedTextBox1.Text);
        }

        public void sendToNC产成品2(string docCode)
        {
            Dictionary<string, NCModel.NCResponseModel> NCModelDIC = new Dictionary<string, NCModel.NCResponseModel>();
            string sql;
            sql = @"SELECT guid, StockInType, WorkShopCode, DocCode, DepartCode, SupplierCode, SupplierName, CreateID, Creator, 
                   CreateDate, ModifyID, Modifier, ModifyDate, ApproverID, Approver, ApproverDate, IsSendToNC, SendToNCDate
                   FROM      Bus_StockInV where docCode='" + docCode + "'";
            DataTable dtHeader = pub.GetDataTable(pub.ConnectionString, sql);

            if (dtHeader != null && dtHeader.Rows.Count > 0)
            {
                //string sqlbody = @"SELECT [guid], [Bguid], [DocCode], [RowNumber], [WorkShopCode], [WarehouseCode], [StorageLocation], [T_CONTRACT_CODE],
                //                [T_ORDER], [T_GOOD_UNIT], [T_GOOD_NUM], [T_GOOD_PRICE], [T_GOOD_MONEY], [VolumeCode], [VolumeCodeNew], [InventoryCode], 
                //                [Size], [Thick], [Width], [Material], [Address], [Weight], [CID], [Virtual], [FaceStatus], [FaceDone], [NetWeight],
                //                [Remark], [ProductDate],Grade,Meter,ZinCeng,PackageType
                //                FROM      Bus_StockInVolume 
                //                where 1=1 and DocCode='" + docCode + "' and VolumeCodeNew is null and VolumeCodeNew <> '' order by RowNumber  ";

                //昨天的
                //string sqlbody = @"SELECT [guid], [Bguid], [DocCode], [RowNumber], [WorkShopCode], [WarehouseCode],WarehouseName, [StorageLocation], [T_CONTRACT_CODE],
                //                [T_ORDER], [T_GOOD_UNIT], [T_GOOD_NUM], [T_GOOD_PRICE], [T_GOOD_MONEY], [VolumeCode], [VolumeCodeNew], [InventoryCode], 
                //                [Size], [Thick], [Width], [Material], [Address], [Weight], [CID], [Virtual], [FaceStatus], [FaceDone], [NetWeight],
                //                [Remark], [ProductDate],Grade,Meter,ZinCeng,PackageType
                //                FROM      Bus_StockInVolume ";
                //sqlbody += " where 1=1 ";
                //sqlbody += " and VolumeCodeNew in (select [批号] from 彩涂2$ unoin all select [批号] from 镀锌2$ unoin all select [批号] from 基板2$) ";
                //sqlbody +=" and [guid]='" + dtHeader.Rows[0]["guid"].ToString() + "' and InventoryCode is not null and InventoryCode <> '' order by RowNumber  ";

                string sqlbody = @"SELECT [guid], [Bguid], [DocCode], [RowNumber], [WorkShopCode], [WarehouseCode],WarehouseName, [StorageLocation], [T_CONTRACT_CODE],
                                [T_ORDER], [T_GOOD_UNIT], [T_GOOD_NUM], [T_GOOD_PRICE], [T_GOOD_MONEY], [VolumeCode], [VolumeCodeNew], [InventoryCode], 
                                [Size], [Thick], [Width], [Material], [Address], [Weight], [CID], [Virtual], [FaceStatus], [FaceDone], [NetWeight],
                                [Remark], [ProductDate],Grade,Meter,ZinCeng,PackageType
                                FROM      Bus_StockInVolume ";
                sqlbody += " where 1=1 ";
                //sqlbody += " and  ProductDate >='2022-10-13' and WarehouseName = '二期无锌花一成品库'";
                //sqlbody += " and [guid]='" + dtHeader.Rows[0]["guid"].ToString() + "' and InventoryCode is not null and InventoryCode <> '' order by RowNumber  ";

                DataTable dtBody = pub.GetDataTable(pub.ConnectionString, sqlbody);
                if (dtBody != null && dtBody.Rows.Count > 0)
                {
                    NCModel.FinishedProductsInBillModel setInboundModel = new NCModel.FinishedProductsInBillModel();
                    //setInboundModel.corpName = "";
                    setInboundModel.region = "华中";
                    //setInboundModel.ceateDate = DateTime.Parse(dtHeader.Rows[0]["CreateDate"].ToString()).ToString("yyyy-MM-dd");
                    //setInboundModel.ceateDate = DateTime.Parse(dtBody.Rows[i]["ProductDate"].ToString()).ToString("yyyy-MM-dd"); ;
                    //查询公司名称 公司编号
                    string sqlworkshop = @"SELECT  [WorkShopName]  FROM [Dic_WorkShop] where WorkShopCode = '3001'";
                    DataTable dtWorkShop = pub.GetDataTable(pub.ConnectionString, sqlworkshop);
                    if (dtWorkShop != null && dtWorkShop.Rows.Count > 0)
                    {
                        setInboundModel.corpName = dtWorkShop.Rows[0]["WorkShopName"].ToString();
                    }
                    else
                    {
                        MessageBox.Show("未能根据当前入库单公司编号查到对应的公司名称");
                        return;
                    }
                    //setInboundModel.cWarehouseName = dtBody.Rows[0]["WarehouseCode"].ToString();
                    //setInboundModel.cWarehouseName = "涪镀锌一线成品库";
                    setInboundModel.cWhsmanagerCode = "";
                    setInboundModel.deptName = "";
                    setInboundModel.cbizCode = "";
                    setInboundModel.remarks = "";

                    List<NCModel.Item> itemList = new List<NCModel.Item>();
                    for (int i = 0; i < dtBody.Rows.Count; i++)
                    {
                        string sqlwareName = "select WarehouseName from Dic_Warehouse where WarehouseCode = '" + dtBody.Rows[i]["WarehouseCode"].ToString() + "'";
                        DataTable dtWareName = pub.GetDataTable(pub.ConnectionString, sqlwareName);
                        if (dtWareName != null && dtWareName.Rows.Count > 0)
                        {
                            setInboundModel.cWarehouseName = dtWareName.Rows[0]["WarehouseName"].ToString();
                        }

                        //setInboundModel.cWarehouseName = dtBody.Rows[i]["WarehouseName"].ToString();
                        NCModel.Item item = new NCModel.Item();
                        //明细ID
                        item.rowNo = dtBody.Rows[i]["Bguid"].ToString();
                        //存货编码
                        item.cinvbascode = dtBody.Rows[i]["InventoryCode"].ToString();
                        //批次号
                        item.vbatchcode = dtBody.Rows[i]["VolumeCodeNew"].ToString(); ;
                        //入库数量
                     
                        item.ninnum = dtBody.Rows[i]["Weight"].ToString();

                        //头部日期
                        DateTime.TryParse(dtBody.Rows[i]["ProductDate"].ToString(),out DateTime dbilldate);
                        setInboundModel.ceateDate = dbilldate.ToString("yyyy-MM-dd");
                        //入库日期
                        item.dbilldate = dbilldate.ToString("yyyy-MM-dd");
                        //颜色
                        item.vfree1 = dtBody.Rows[i]["FaceDone"].ToString();
                        //长度
                        item.vfree2 = dtBody.Rows[i]["Meter"].ToString();
                        //产地
                        if (string.IsNullOrEmpty(dtBody.Rows[i]["Address"].ToString()))
                        {
                            item.vfree3 = "万达";
                        }
                        else
                        {
                            item.vfree3 = dtBody.Rows[i]["Address"].ToString();
                        }
                        
                        //表面状态
                        item.vfree4 = dtBody.Rows[i]["FaceStatus"].ToString();
                        //表面厚度
                        item.vfree5 = "0";
                        //等级
                        item.vuserdef8 = dtBody.Rows[i]["Grade"].ToString();

                        item.nprice = "";
                        item.nmny = "";
                        item.pk_defdoc11 = "";
                        item.pk_defdoc12 = "";
                        item.vnotebody = "";
                        item.vuserdef9 = "";
                        item.vuserdef10 = dtBody.Rows[i]["PackageType"].ToString();
                        //客户
                        item.pk_defdoc13 = "";
                        DateTime.TryParse(dtBody.Rows[i]["ProductDate"].ToString(), out DateTime date);
                        item.scrq = date.ToString("yyyy-MM-dd");
                        itemList.Add(item);

                        //推
                        setInboundModel.items = itemList;
                        string jsonStr = JsonConvert.SerializeObject(setInboundModel);

                        //XmlDocument xml  = (XmlDocument)JsonConvert.DeserializeXmlNode(jsonStr,"root");
                        ExternalSystemToNcItfPortTypeClient client = new ExternalSystemToNcItfPortTypeClient();
                        string responseStr = client.finishedProductsInBill(jsonStr);
                        NCModel.NCResponseModel nCResponse = JsonConvert.DeserializeObject<NCModel.NCResponseModel>(responseStr);
                        //
                        NCModelDIC.Add(item.vbatchcode, nCResponse);

                        string sqllog = "insert into table_1(ssss,code) values('" +  nCResponse?.msg?.ToString() + "','"+ item.vbatchcode + "')";
                        pub.ExecuteSql(pub.ConnectionString,sqllog);
                        itemList.Clear();
                    }


                    setInboundModel.items = itemList;
                    
                    //string jsonStr = JsonConvert.SerializeObject(setInboundModel);

                    ////XmlDocument xml  = (XmlDocument)JsonConvert.DeserializeXmlNode(jsonStr,"root");
                    //WMS2NC.ExternalSystemToNcItfPortTypeClient client = new WMS2NC.ExternalSystemToNcItfPortTypeClient();
                    //string responseStr = client.finishedProductsInBill(jsonStr);
                    //NCModel.NCResponseModel nCResponse = JsonConvert.DeserializeObject<NCModel.NCResponseModel>(responseStr);
                    ////调用成功，改写NC状态
                    //if (nCResponse.state == 0)
                    //{
                    //    string sqlUpdate = @"update Bus_StockInV set SendToNCReturnValue = '" + nCResponse.result + "',IsSendToNC = 'Y' ,SendToNCDate = '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' where docCode = '" + docCode + "'";
                    //    int r = pub.ExecuteSql(pub.ConnectionString, sqlUpdate, "原料卷入库发送到NC");
                    //    if (r < 1)
                    //    {
                    //        MessageBox.Show("更新是否成功发送到NC失败");
                    //    }
                    //}
                    //MessageBox.Show("抛送NC结果：" + nCResponse.msg);
                }
                else
                {
                    MessageBox.Show("没查到行信息");
                }
            }
        }
    }
}
